package cc.spider.web.processor;


import cc.spider.core.IDataProcessor;
import cc.spider.model.FlowData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestProcess implements IDataProcessor {
    @Override
    public void process(FlowData flowData) {
        /*Response<String> response = (Response<String>) flowData.getResultInfo();
        Map<String, Object> map = JSON.parseObject(response.getResult(), Map.class);
        flowData.setFields(map);*/
        try {
            String content = readResources("parse.html");
            ScriptEngineManager engineManager = new ScriptEngineManager();
            ScriptEngine scriptEngine = (ScriptEngine) engineManager.getEngineByName("JavaScript");
            Compilable compilable = (Compilable) scriptEngine;
            CompiledScript compiledScript = compilable.compile("document.select('section')");
            long startTime = System.currentTimeMillis();
            int i = 100000;
            while (--i > 0){
                Document doc = Jsoup.parse(content);
                scriptEngine.put("document", doc);
                Elements els = (Elements) compiledScript.eval();
            }
            long endTime = System.currentTimeMillis();
            System.out.println("执行时间:" + (endTime - startTime));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(flowData.getResultInfo().getResult());
    }

    private String readResources(String fileName) throws IOException {
        InputStream fis = null;
        fis = getClass().getClassLoader().getResourceAsStream(fileName);
        byte[] bytes = new byte[1024];
        int len = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = fis.read(bytes)) != -1) {
            baos.write(bytes, 0, len);
        }
        return baos.toString();
    }
}
